home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 August: Tool Chest / Dev.CD Aug 00 TC Disk 2.toast / pc / sample code / quicktime / wired movies and sprites / qtwiredsprites / common files / imagecompressionutilities.c < prev    next >
Encoding:
Text File  |  2000-06-23  |  23.9 KB  |  803 lines

  1. //////////
  2. //
  3. //    File:        ImageCompressionUtilities.c
  4. //
  5. //    Contains:    Image Compression Utilities.
  6. //
  7. //    Written by:    Peter Hoddie, Sean Allen, Chris Flick
  8. //    Revised by:    Tim Monroe
  9. //
  10. //    Copyright:    © 1998 by Apple Computer, Inc., all rights reserved.
  11. //
  12. //    Change History (most recent first):
  13. //
  14. //       <4>         12/16/98    rtm        removed orphaned prototype for compressTransparentRLEwithHitTesting
  15. //       <3>         05/28/98    rtm        added some typecasting to minimize MSDev compiler warnings
  16. //       <2>         03/22/98    rtm        made changes to RecompressPictureFileWithTransparency, as per Chris' fixes
  17. //       <1>         03/27/98    rtm        existing file
  18. //
  19. //////////
  20.  
  21.  
  22. #ifndef __COLORPICKER__
  23. #include <ColorPicker.h>
  24. #endif
  25.  
  26. #ifndef __RESOURCES__
  27. #include <Resources.h>
  28. #endif
  29.  
  30. #ifndef __ENDIAN__
  31. #include <Endian.h>
  32. #endif
  33.  
  34. #ifndef _IMAGECOMPRESSIONUTILITIES_
  35. #include "ImageCompressionUtilities.h"
  36. #endif
  37.  
  38. pascal void extractStdPix( PixMap *src, Rect *srcRect, MatrixRecord *matrix, short mode, RgnHandle mask, PixMap *matte, Rect *matteRect, short flags );
  39. static ImageDescriptionHandle createImageDescription( CodecType cType, PixMapHandle pixmap );
  40. static void DrawPictureNoDither(PicHandle pic, const Rect *bounds);
  41. static OSErr prepareFor16BitCompress(PicHandle *pic);
  42.  
  43. // We use the Animation compressor at 16 bit depth in these utilities
  44. #define kCompressDepth    16
  45.  
  46. // Used for compressing QuickDraw pictures with transparency/hittesting
  47.  
  48. typedef struct {
  49.     PicHandle    picture;
  50. } PictureCompressProcData;
  51.  
  52. static pascal OSErr myPictureCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType portType, void * refcon );
  53.  
  54.  
  55. // Used for recompressing QuickTime compressed data with transparency/hittesting
  56.  
  57. typedef struct {
  58.     ImageDescriptionHandle    imageDesc;
  59.     Handle                    imageData;
  60. } CompressedImageCompressProcData;
  61.  
  62.  
  63. static pascal OSErr myImageCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType portType, void * refcon );
  64.  
  65.  
  66. // A few macros to help with error handling
  67. #define        BailIf(a, e)         {if (a)     { err = e; goto bail; }}
  68. #define        BailOSErr(a)         {if ((err = a) != noErr)    goto bail;}
  69. #define        BailMemErr(a)        {a; if ((err = MemError()) != noErr) goto bail;}
  70.  
  71.  
  72. // PICT to compressed image conversion
  73.  
  74. //    Given a QuickDraw picture, extract QuickTime compressed image data and description, if any.
  75. //
  76. //    It does this by creating a temporary CGrafPort, installing a QuickDraw bottleneck
  77. //    routine for the StdPix call, and then drawing the picture. Since this routine will
  78. //    be called whenever QuickTime compressed image data is encountered, it can
  79. //    stash away any found compressed data and description. On DrawPicture's return, the
  80. //    stashed data and description is retrieved and returned to the caller.
  81. //
  82. //    Worth noting in this utility is definition of the extractPictRecord. This is a 
  83. //    structure consisting of a CGrafPort structure followed by fields for a handle to 
  84. //    image data and an ImageDescription. This layout allows ExtractCompressData to open
  85. //    a CGrafPort using the embedded CGrafPort field, and set this as the current port. 
  86. //    Then, in the StdPix routine extractStdPix, the current port can be retrieved and 
  87. //    cast to a pointer to an extractPictRecord to get access to the other fields.
  88. //
  89.  
  90. typedef struct {
  91.     CGrafPort tempPort;
  92.  
  93.     Handle data;
  94.     ImageDescriptionHandle idh;
  95. } extractPictRecord;
  96.  
  97.  
  98. OSErr ExtractCompressData( PicHandle thePict, Handle *dataOut, ImageDescriptionHandle *idh )
  99. {
  100.     OSErr                err = noErr;
  101.     extractPictRecord     state;
  102.     CQDProcs             procs;
  103.     GrafPtr             savePort;
  104.     Rect                 bounds;
  105.  
  106.     if ( dataOut )
  107.         *dataOut = nil;
  108.     if ( idh )
  109.         *idh = nil;
  110.  
  111.     GetPort( &savePort );
  112.  
  113.     OpenCPort( &state.tempPort );
  114.     SetStdCProcs( &procs );
  115.     procs.newProc1 = (UniversalProcPtr)NewStdPixProc(extractStdPix);
  116.     state.tempPort.grafProcs = &procs;
  117.  
  118.     state.data = nil;
  119.     state.idh = nil;
  120.  
  121.     MacSetPort( (GrafPtr)&state.tempPort );
  122.     HidePen();
  123.  
  124.     bounds = (**thePict).picFrame;
  125.     DrawPicture(thePict, &bounds);    
  126.  
  127.     MacSetPort( savePort );
  128.     CloseCPort( &state.tempPort );
  129.  
  130.     DisposeRoutineDescriptor( procs.newProc1 );
  131.     
  132.     *dataOut    = state.data;
  133.     *idh        = state.idh;
  134.  
  135.     return err;
  136. }
  137.  
  138. pascal void extractStdPix( PixMap *src, Rect *srcRect, MatrixRecord *matrix, short mode, RgnHandle mask, PixMap *matte, Rect *matteRect, short flags )
  139. {
  140. #if TARGET_OS_MAC
  141. #pragma unused(srcRect,matrix,mode,mask,matte,matteRect,flags)
  142. #endif
  143.     extractPictRecord    *state;
  144.  
  145.     GetPort( (GrafPtr *)&state );
  146.  
  147.     if  ( state->idh == nil ) {
  148.         ImageDescriptionHandle    desc;
  149.         Ptr                     data;
  150.         long                    bufferSize;
  151.  
  152.         if ( GetCompressedPixMapInfo(src, &desc, &data, &bufferSize, nil, nil) == noErr ) {
  153.             state->idh = desc;
  154.             HandToHand( (Handle *)&state->idh );
  155.             PtrToHand( data, &state->data, bufferSize );
  156.         }
  157.     }
  158. }
  159.  
  160.  
  161. static ImageDescriptionHandle createImageDescription( CodecType cType, PixMapHandle pixmap )
  162. {
  163.     ImageDescriptionHandle    desc = nil;
  164.     
  165.     if ( ( desc = (ImageDescription **)NewHandleClear(sizeof(ImageDescription)) ) != nil ) {
  166.         ImageDescription     *dp = *desc;
  167.         Rect                bounds = (**pixmap).bounds;
  168.  
  169.         dp->idSize             = sizeof(ImageDescription);
  170.         dp->cType             = cType;    
  171.         dp->spatialQuality     = codecNormalQuality;
  172.         dp->width            = bounds.right - bounds.left;
  173.         dp->height             = bounds.bottom - bounds.top;
  174.         dp->hRes             = 72L << 16;
  175.         dp->vRes             = 72L << 16;
  176.         dp->dataSize         = ((**pixmap).rowBytes & 0x3fff) * dp->height;
  177.         dp->depth             = (**pixmap).pixelSize;
  178.         dp->clutID             = -1;
  179.         
  180.         if ( SetImageDescriptionCTable( desc, (**pixmap).pmTable ) ) {
  181.             DisposeHandle( (Handle) desc );
  182.             desc = nil;
  183.         }
  184.     }
  185.     return desc;
  186. }
  187.  
  188. pascal void noDitherBitsProc(const BitMap *srcBits, const Rect *srcRect, const Rect *dstRect, short mode, RgnHandle maskRgn);
  189. pascal void noDitherBitsProc(const BitMap *srcBits, const Rect *srcRect, const Rect *dstRect, short mode, RgnHandle maskRgn)
  190. {
  191.     mode &= ~ditherCopy;
  192.     StdBits(srcBits, srcRect, dstRect, mode, maskRgn);
  193. }
  194.  
  195. //    DrawPictureNoDither is used to draw a QuickDraw picture but to turn convert any
  196. //    use of ditherCopy graphics modes to graphics modes that don't use ditherCopy. It
  197. //    only performs this with the stdbits bottleneck routine. Since ditherCopy is simply
  198. //    ORed in with other graphics modes, the replaced bottleneck routine only needs to
  199. //    AND off the ditherCopy flag.
  200. void DrawPictureNoDither(PicHandle pic, const Rect *bounds)
  201. {        
  202.     CQDProcs procs;
  203.     GrafPtr savePort;
  204.     CQDProcsPtr saveProcs;
  205.  
  206.     GetPort(&savePort);
  207.     saveProcs = (CQDProcsPtr)savePort->grafProcs;
  208.     SetStdCProcs( &procs );
  209.  
  210.     procs.bitsProc = (QDBitsUPP)NewQDBitsProc(noDitherBitsProc);
  211.     savePort->grafProcs = (QDProcs *)&procs;
  212.  
  213.     DrawPicture(pic, bounds);
  214.  
  215.     savePort->grafProcs = (QDProcs *)saveProcs;
  216.  
  217.     DisposeRoutineDescriptor( procs.bitsProc );
  218. }
  219.  
  220.  
  221. //
  222. // The following is a routine that can be used to clean up the colors in a picture
  223. // before being compressed with the Animation compressor in 16-bits at codecNormal
  224. // quality. The QuickTime Animation compressor can operate in both a lossless and
  225. // lossy manner. This routine is meant to help when compressing in a lossy manner.
  226. //
  227. // By clean up, what's meant is the forcing of any colors that are sufficiently close
  228. // to white to colors that are not as close. Since the Animation compressor will
  229. // perform threshholding of the image's colors when codecNormal quality is specified,
  230. // without this preprocessing, colors very close to white can be mapped to white
  231. // in the compression. If white was chosen as the key color, pixels that are
  232. // close to white could possibly become transparent as well.
  233. //
  234. // While not used by other routines in this file, prepareFor16BitCompress is provided
  235. // as an example of how this might be done.
  236. //
  237. // Note that with codecLossless quality, there is no remapping of colors so this
  238. // step is unnecessary.
  239. //
  240.  
  241. #define kThreshold (255 - 16)
  242.  
  243. OSErr prepareFor16BitCompress(PicHandle *pic)
  244. {
  245.     OSErr err = noErr;
  246.     PicHandle newPicture = nil;
  247.     Rect r;
  248.     GWorldPtr gw = nil;
  249.     CGrafPtr savePort;
  250.     GDHandle saveGD;
  251.     short rowBytes;
  252.     Ptr baseAddr;
  253.     long w, h;
  254.     PixMapHandle pm;
  255.  
  256.     GetGWorld(&savePort, &saveGD);
  257.  
  258.     r = (***pic).picFrame;
  259.     MacOffsetRect(&r, (short)-r.left, (short)-r.top);
  260.  
  261.     err = NewGWorld(&gw, 32, &r, nil, nil, useTempMem);
  262.     if (err) {
  263.         err = NewGWorld(&gw, 32, &r, nil, nil, 0);
  264.         if (err) goto bail;
  265.     }
  266.  
  267.     pm = GetGWorldPixMap(gw);
  268.     LockPixels(pm);
  269.     SetGWorld(gw, nil);
  270.     EraseRect(&r);
  271.  
  272.     DrawPicture(*pic, &r);
  273.  
  274.     baseAddr = GetPixBaseAddr(pm);
  275.     rowBytes = (**pm).rowBytes & 0x3fff;
  276.     for (h=0; h<r.bottom; h++) {
  277.         long *pixelPtr = (long *)baseAddr;
  278.  
  279.         for (w=0; w<r.right; w++, pixelPtr++) {
  280.             UInt8 r, g, b, a;
  281.             long pixel = *pixelPtr;
  282.  
  283.             if ((pixel & 0x0ffffff) == 0x00ffffff)        // pure white
  284.                 continue;
  285.  
  286.             a = (pixel >> 24) & 0x0ff;
  287.             r = (pixel >> 16) & 0x0ff;
  288.             g = (pixel >>  8) & 0x0ff;
  289.             b = (pixel >>  0) & 0x0ff;
  290.             if ((r > kThreshold) && (g > kThreshold) && (b > kThreshold)) {
  291.                 r = g = b = kThreshold;
  292.                 *pixelPtr = (a << 24) | (kThreshold << 16) | (kThreshold << 8) | (kThreshold << 0);
  293.             }
  294.         }
  295.  
  296.         baseAddr += rowBytes;
  297.     }
  298.  
  299.     newPicture = OpenPicture(&r);
  300.     CopyBits((BitMap *)&gw->portPixMap, (BitMap *)&gw->portPixMap, &r, &r, ditherCopy, nil);
  301.     ClosePicture();
  302.     UnlockPixels(pm);
  303.  
  304. bail:
  305.     if (gw)
  306.         DisposeGWorld(gw);
  307.  
  308.     if (err == noErr) {
  309.         if (newPicture) {
  310.             KillPicture(*pic);
  311.             *pic = newPicture;
  312.         }
  313.     }
  314.  
  315.     SetGWorld(savePort, saveGD);
  316.  
  317.     return err;
  318. }
  319.  
  320.  
  321. /*
  322.     ---------------- Callback based routines for compressing with hittesting and transparency ----------------
  323.  */
  324.  
  325. /*
  326.     RecompressWithTransparencyFromProc
  327.     
  328.     This is a routine either called indirectly through RecompressCompressedImageWithTransparency, 
  329.     RecompressPictureWithTransparency, or RecompressPictureFileWithTransparency or called directly.
  330.     It takes a callback procedure which is responsible for returning the dimensions of the
  331.     area of some type of drawable entity and for actually drawing that entity.
  332.     
  333.         includeHitTesting        TRUE if hit testing data should be added to the compressed data
  334.         keyColor                A RGBColor that should be used as the transparency color. Pass nil
  335.                                 if the image doesn't have transparent portions.
  336.         hitTestRegion            A RgnHandle specifying an area that is to be used as the hit test
  337.                                 area. If you pass this, you must also set includeHitTesting to TRUE.
  338.                                 This is optional as the callback procedure can perform drawing
  339.                                 itself of the hit test area which is often suitable when both the
  340.                                 image and hit test area were painted in a drawing program.
  341.         idh                        Returned ImageDescriptionHandle for the compressed image data
  342.         imageData                Returned Handle to the compressed image data
  343.  
  344.  */
  345. OSErr RecompressWithTransparencyFromProc( CompressDrawProc drawProc, void * drawProcRefcon, 
  346.                                                     Boolean includeHitTesting,
  347.                                                     RGBColor *keyColor, 
  348.                                                     RgnHandle hitTestRegion,
  349.                                                     ImageDescriptionHandle *idh, Handle * imageData )
  350. {
  351.     OSErr                         err = noErr;
  352.     Rect                        bounds;
  353.     CGrafPtr                    savePort;
  354.     GDHandle                    saveDevice;
  355.     GWorldPtr                    gwImage = nil;        // always used
  356.     GWorldPtr                    gwPrev = nil;        // used if compressing with transparency (via keycolor)
  357.     GWorldPtr                    gwMap = nil;        // used if compressing with hittesting data
  358.     ImageDescriptionHandle        desc = nil;            // resulting image description
  359.     ImageDescriptionHandle        gwMapDesc = nil;
  360.     ImageSequence                seq = 0;            // compress sequence
  361.     ImageSequenceDataSource        mapSource = 0L;
  362.     Ptr                            data = nil;
  363.     long                         dataSize;
  364.     UInt8                         similarity;
  365.     Boolean                        includeTransparency = false;
  366.     RGBColor                    saveBackColor;
  367.         
  368.     GetGWorld( &savePort, &saveDevice );
  369.     
  370.     if( !drawProc || !idh || !imageData ){
  371.         err = paramErr;
  372.         goto bail;
  373.     }
  374.     
  375.     // tell callback that it should initialize any storage it needs
  376.     err = drawProc( kRecoProcInitMsg, nil, nil, 0, drawProcRefcon );
  377.     if(err) goto bail;
  378.     
  379.     // determine bounds to use for compression
  380.     err = drawProc( kRecoProcGetBoundsMsg, &bounds, nil, 0, drawProcRefcon );
  381.     if(err) goto bail;
  382.     
  383.     err = QTNewGWorld(&gwImage, kCompressDepth, &bounds, nil, nil, kICMTempThenAppMemory);
  384.     if(err) goto bail;
  385.  
  386.     if( keyColor ) {
  387.         includeTransparency = true;
  388.     }
  389.     
  390.     // Include hit testing? If so, we need a previous buffer and an 8-bit GWorld for the mask data
  391.     if( includeHitTesting ) {
  392.         err = QTNewGWorld(&gwPrev, kCompressDepth, &bounds, nil, nil, kICMTempThenAppMemory);
  393.         if(err) goto bail;
  394.  
  395.         err = QTNewGWorld(&gwMap, 8, &bounds, nil, nil, kICMTempThenAppMemory);
  396.         if(err) goto bail;
  397.     }
  398.     
  399.     LockPixels( GetGWorldPixMap(gwImage) );
  400.     
  401.     if( gwPrev )
  402.         LockPixels( GetGWorldPixMap(gwPrev) );
  403.     
  404.     if( gwMap )
  405.         LockPixels( GetGWorldPixMap(gwMap) );
  406.     
  407.     if(gwPrev) {
  408.         SetGWorld( gwPrev, nil );
  409.         ClipRect( &bounds );
  410.         
  411.         GetBackColor( &saveBackColor );
  412.         if( keyColor )
  413.             RGBBackColor( keyColor );
  414.         
  415.             EraseRect( &bounds );
  416.             
  417.         RGBBackColor( &saveBackColor );
  418.     }
  419.     
  420.     if( gwMap ) {
  421.         SetGWorld( gwMap, nil );
  422.         
  423.         EraseRect( &bounds );            // paint background white
  424.  
  425.         err = drawProc( kRecoProcDrawMsg, &bounds, gwMap, kRecoProcHitTestingImageType, drawProcRefcon );
  426.         if(err) goto bail;
  427.         
  428.         if( hitTestRegion ) {
  429.             RGBColor blackRGB;
  430.             
  431.             blackRGB.red = blackRGB.green = blackRGB.blue = 0;
  432.             
  433.             RGBForeColor( &blackRGB );
  434.             MacPaintRgn( hitTestRegion );
  435.         }
  436.  
  437.         gwMapDesc = createImageDescription(kRawCodecType, GetGWorldPixMap(gwMap));
  438.         err = MemError();
  439.         if(err) goto bail;
  440.     }
  441.     
  442.     SetGWorld( gwImage, nil );
  443.     ClipRect( &bounds );
  444.     EraseRect( &bounds );
  445.     
  446.     desc = (ImageDescriptionHandle) NewHandle(sizeof(ImageDescription));
  447.  
  448.  
  449.     // NOTE: We pass codecLosslessQuality so that the key color if any is matched exactly. This avoids colors within
  450.     // some threshhold different from the key color being taken as equivalent to the key color. Alternatively, we
  451.     // could perform some threshhold processing on the source image's pixels and pass codecNormalQuality.
  452.     if( includeHitTesting ) {
  453.         // Allocate a compression sequence and add source data for hittest mask
  454.         err = CompressSequenceBegin(&seq, GetGWorldPixMap(gwPrev), nil, nil, nil, kCompressDepth, kAnimationCodecType, 
  455.                                             anyCodec, codecLosslessQuality, codecLosslessQuality, 2, nil, 0, desc);
  456.  
  457.         // with hit testing, we have to add a data source to hold the mask data
  458.         err = CDSequenceNewDataSource(seq, &mapSource, kRecoProcHitTestingImageType, 1, (Handle)gwMapDesc, nil, nil);
  459.         if (err) goto bail;
  460.  
  461.         err = CDSequenceSetSourceData(mapSource, GetPixBaseAddr(GetGWorldPixMap(gwMap)), (**gwMapDesc).dataSize);
  462.         if (err) goto bail;
  463.  
  464.         // What's the maximum size the compressed data could be--including hit-test data?
  465.         err = GetCSequenceMaxCompressionSize(seq, GetGWorldPixMap(gwPrev), &dataSize);
  466.     }
  467.     else
  468.     {    // not hit-testing so we only need the image buffer
  469.         err = CompressSequenceBegin( &seq, GetGWorldPixMap(gwImage), nil, &bounds, nil, kCompressDepth, kAnimationCodecType, 0, 
  470.                                     codecLosslessQuality, codecLosslessQuality, 2, nil, 0, desc );
  471.         if(err) goto bail;
  472.         
  473.         // What's the maximum size the compressed data could be?
  474.         err = GetCSequenceMaxCompressionSize(seq, GetGWorldPixMap(gwImage), &dataSize);
  475.     }
  476.     if (err) goto bail;
  477.     
  478.  
  479.     data = NewPtr( dataSize );
  480.     if( err = MemError()) goto bail;
  481.     
  482.     if( includeHitTesting /* with or without transparency */ ) {
  483.         // With hittesting, we use two buffers. Actually we don't have to but do so to show how it can be
  484.         // done. Also, this code was based upon some older code that did.
  485.         
  486.         
  487.         // compress the GWorld painted with the keyColor exclusively
  488.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwPrev), nil, 0, data, &dataSize, &similarity, nil );
  489.         if ( err ) goto bail;
  490.  
  491.         err = SetCSequencePrev(seq, GetGWorldPixMap(gwPrev), nil);
  492.         if (err) goto bail;
  493.  
  494.         // draw the image into the GWorld over area painted with keyColor so that if picture is transparent already
  495.         // areas it doesn't paint will be in the key color
  496.         SetGWorld( gwImage, nil );
  497.         
  498.         GetBackColor( &saveBackColor );
  499.         if( keyColor )
  500.             RGBBackColor( keyColor );
  501.             
  502.             EraseRect( &bounds );
  503.         
  504.         RGBBackColor( &saveBackColor );
  505.     
  506.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  507.         if(err) goto bail;
  508.  
  509.         // now compress the GWorld holding the image drawn on top of the keyColor
  510.         err = CompressSequenceFrame(seq, GetGWorldPixMap(gwImage), nil, 0, data, &dataSize, &similarity, nil);
  511.         if (err) goto bail;
  512.         
  513.         // At this point, data points to the image data for just the difference between the two (thus generating transparency) 
  514.         // Also, hit testing data is contained in the image data if it was specified.
  515.     }
  516.     else if( includeTransparency ) {
  517.         // For transparency case without hittesting, we get by with only using a single buffer so we special case the
  518.         // code here. This is also for clarity.
  519.     
  520.         // compress the GWorld painted with the keyColor exclusively
  521.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwImage), nil, codecFlagUpdatePrevious, data, &dataSize, &similarity, nil );
  522.         if ( err ) goto bail;
  523.  
  524.         // draw the image into the GWorld over area painted with keyColor so that if picture is transparent already
  525.         // areas it doesn't paint will be in the key color
  526.         SetGWorld( gwImage, nil );
  527.         
  528.         GetBackColor( &saveBackColor );
  529.         if( keyColor )
  530.             RGBBackColor( keyColor );
  531.             
  532.             EraseRect( &bounds );
  533.         
  534.         RGBBackColor( &saveBackColor );
  535.     
  536.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  537.         if(err) goto bail;
  538.  
  539.         // now compress the GWorld holding the image drawn on top of the keyColor
  540.         err = CompressSequenceFrame(seq, GetGWorldPixMap(gwImage), nil, codecFlagUpdatePrevious, data, &dataSize, &similarity, nil);
  541.         if (err) goto bail;
  542.         
  543.         // At this point, data points to the image data for just the difference between the two (thus generating transparency) 
  544.         // Also, hit testing data is contained in the image data if it was specified.
  545.     }
  546.     else
  547.     {
  548.         SetGWorld( gwImage, nil );
  549.  
  550.         // draw the image into the GWorld
  551.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  552.         if(err) goto bail;
  553.  
  554.         // compress the GWorld containing the image painted on white
  555.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwImage), nil, 0, data, &dataSize, &similarity, nil );
  556.         if ( err ) goto bail;
  557.         
  558.         // At this point, data points to the image data for just the image, newly compressed. Also, hit testing data is contained
  559.         // in the image data if it was specified.
  560.     }
  561.     
  562.     CDSequenceEnd( seq );
  563.     seq = 0;
  564.     
  565.     // free the GWorlds and drop references so we have more memory for PtrToHand
  566.     if( gwImage )    DisposeGWorld( gwImage );
  567.     gwImage = nil;
  568.     if( gwMap )    DisposeGWorld( gwMap );
  569.     gwMap = nil;
  570.     if( gwPrev ) DisposeGWorld( gwPrev );
  571.     gwPrev = nil;
  572.     
  573.     err = PtrToHand( data, imageData, dataSize );
  574.     if ( err ) goto bail;
  575.     
  576.     *idh = desc;
  577.     desc = nil;                // forget about this name for ImageDescriptionHandle so dispose below doesn't catch it
  578.     
  579. bail:
  580.     // tell callback to dispose of anything it allocated. We pass 'err ' in portType if an error occurred
  581.     drawProc( kRecoProcDisposeMsg, nil, nil, err ? FOUR_CHAR_CODE('err ') : 0, drawProcRefcon );
  582.     
  583.     CDSequenceEnd( seq );
  584.     SetGWorld( savePort, saveDevice );
  585.     
  586.     if(gwImage)        DisposeGWorld( gwImage );
  587.     if(gwMap )        DisposeGWorld( gwMap );
  588.     if(gwPrev )        DisposeGWorld( gwPrev );
  589.     if(desc)         DisposeHandle((Handle) desc );
  590.     if(gwMapDesc)    DisposeHandle((Handle) gwMapDesc );
  591.     if(data)        DisposePtr( data );
  592.         
  593.     return err;
  594. }
  595.  
  596.  
  597. /*
  598.     myPictureCompressDrawProc
  599.     
  600.     Helper routine to be used with RecompressWithTransparencyFromProc to compress QuickDraw Pictures.
  601.  */
  602.  
  603. static pascal OSErr myPictureCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType drawingImageType, void * refcon )
  604. {
  605. #if TARGET_OS_MAC
  606. #pragma unused(drawingPort)
  607. #endif
  608.     OSErr err = noErr;
  609.     PictureCompressProcData * data = refcon;
  610.     Rect r;
  611.     
  612.     switch( message ) {
  613.         case kRecoProcInitMsg:
  614.             break;
  615.             
  616.         case kRecoProcDisposeMsg:
  617.             break;
  618.             
  619.         case kRecoProcGetBoundsMsg:
  620.             r = (**data->picture).picFrame;
  621.             
  622.             r.left = EndianS16_BtoN(r.left);
  623.             r.top = EndianS16_BtoN(r.top);
  624.             r.bottom = EndianS16_BtoN(r.bottom);
  625.             r.right = EndianS16_BtoN(r.right);
  626.             
  627.             MacOffsetRect(&r, (short)-r.left, (short)-r.top );
  628.             
  629.             *bounds = r;
  630.             break;
  631.             
  632.         case kRecoProcDrawMsg:
  633.             r = (**data->picture).picFrame;
  634.             
  635.             r.left = EndianS16_BtoN(r.left);
  636.             r.top = EndianS16_BtoN(r.top);
  637.             r.bottom = EndianS16_BtoN(r.bottom);
  638.             r.right = EndianS16_BtoN(r.right);
  639.  
  640.             MacOffsetRect( &r, (short)-r.left, (short)-r.top );
  641.  
  642.             if( kRecoProcOriginalImageType == drawingImageType )
  643.                 DrawPictureNoDither( data->picture, &r );
  644.             break;
  645.         default:
  646.             err = -1;
  647.     }
  648.  
  649.     return err;
  650. }    
  651.     
  652.  
  653. /*
  654.     myImageCompressDrawProc
  655.     
  656.     Helper routine to be used with RecompressWithTransparencyFromProc to compress QuickTime compressed image data.
  657.  */
  658. static pascal OSErr myImageCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType drawingImageType, void * refcon )
  659. {
  660. #if TARGET_OS_MAC
  661. #pragma unused(drawingImageType)
  662. #endif
  663.  
  664.     OSErr err = noErr;
  665.     CompressedImageCompressProcData * data = refcon;
  666.     Rect r;
  667.     
  668.     switch( message ) {
  669.     case kRecoProcInitMsg:
  670.         break;
  671.     case kRecoProcDisposeMsg:
  672.         break;
  673.     case kRecoProcGetBoundsMsg:
  674.         r.left = r.top = 0;
  675.         r.right = (**data->imageDesc).width;
  676.         r.bottom = (**data->imageDesc).height;
  677.         
  678.         *bounds = r;
  679.         break;
  680.     case kRecoProcDrawMsg:
  681.         {
  682.             SignedByte saveState;
  683.             
  684.             r.left = r.top = 0;
  685.             r.right = (**data->imageDesc).width;
  686.             r.bottom = (**data->imageDesc).height;
  687.             
  688.             saveState = HGetState( data->imageData );
  689.             HLockHi( data->imageData );
  690.             
  691.             if( kRecoProcOriginalImageType == drawingImageType )
  692.                 err = DecompressImage( *data->imageData, data->imageDesc, GetGWorldPixMap(drawingPort), &r, &r, srcCopy, nil );
  693.             
  694.             HSetState( data->imageData, saveState );
  695.         }
  696.         break;
  697.     default:
  698.         err = -1;
  699.     }
  700.  
  701.     return err;
  702. }    
  703.  
  704.  
  705.  
  706. /*
  707.     RecompressCompressedImageWithTransparency
  708.     
  709.     Given an ImageDescriptionHandle and a handle to image data, generate new RLE compressed data
  710.     with optional hitTesting and transparency.
  711.  */
  712. OSErr RecompressCompressedImageWithTransparency( ImageDescriptionHandle originalDesc, Handle originalImageData,
  713.                                         RGBColor *keyColor, 
  714.                                         RgnHandle hitTestRegion,
  715.                                         ImageDescriptionHandle *idh, Handle * imageData )
  716. {
  717.     OSErr err = noErr;
  718.     CompressedImageCompressProcData params;
  719.     
  720.     params.imageDesc = originalDesc;
  721.     params.imageData = originalImageData;
  722.     
  723.     err = RecompressWithTransparencyFromProc( myImageCompressDrawProc, ¶ms, 
  724.                                         (Boolean)(hitTestRegion != nil), 
  725.                                         keyColor, 
  726.                                         hitTestRegion, 
  727.                                         idh, imageData );
  728.     
  729.     return err;
  730. }
  731.  
  732. /*
  733.     RecompressPictureWithTransparency
  734.     
  735.     Given a QuickDraw PicHandle, generate new RLE compressed data with optional hitTesting and transparency.
  736.  */
  737. OSErr RecompressPictureWithTransparency( PicHandle originalPicture,
  738.                                         RGBColor *keyColor, 
  739.                                         RgnHandle hitTestRegion,
  740.                                         ImageDescriptionHandle *idh, Handle * imageData )
  741. {
  742.     OSErr err = noErr;
  743.     PictureCompressProcData params;
  744.     
  745.     params.picture = originalPicture;
  746.     
  747.     err = RecompressWithTransparencyFromProc( myPictureCompressDrawProc, ¶ms, 
  748.                                         (Boolean)(hitTestRegion != nil), 
  749.                                         keyColor, 
  750.                                         hitTestRegion, 
  751.                                         idh, imageData );
  752.     
  753.     return err;
  754. }
  755.  
  756. /*
  757.     RecompressPictureFileWithTransparency
  758.     
  759.     Given a QuickDraw PICT file, generate new RLE compressed data with optional hitTesting and transparency.
  760.     This function uses GetCompressedImageFromPicture to do the actual work on the PicHandle retrieved from
  761.     the PICT file.
  762.  */
  763. OSErr RecompressPictureFileWithTransparency( FSSpec * spec, 
  764.                                         RGBColor *keyColor, 
  765.                                         RgnHandle hitTestRegion,
  766.                                         ImageDescriptionHandle *idh, Handle * imageData )
  767. {
  768.     OSErr         err = noErr;
  769.     short        sourceRefNum = 0;
  770.     PicHandle    picture = nil;
  771.     long        eof;
  772.     long        countBytes;
  773.     
  774.     *idh = nil;
  775.     *imageData = nil;    
  776.     
  777.     BailOSErr(FSpOpenDF( spec, fsRdPerm, &sourceRefNum ));
  778.     
  779.     BailOSErr(GetEOF( sourceRefNum, &eof ));
  780.     eof -= 512;
  781.     
  782.     BailOSErr(SetFPos( sourceRefNum, fsFromStart, 512 ));
  783.             
  784.     picture = (PicHandle) NewHandle(eof);
  785.     err = MemError();
  786.     BailOSErr(err);
  787.  
  788.     countBytes = eof;
  789.     HLock((Handle) picture);
  790.     BailOSErr( FSRead( sourceRefNum, &countBytes, *picture) );
  791.     HUnlock((Handle) picture);
  792.     
  793.     BailOSErr( RecompressPictureWithTransparency( picture,  keyColor, hitTestRegion,
  794.                                 idh, imageData ));
  795.                                 
  796. bail:
  797.     if ( picture )            DisposeHandle((Handle) picture );
  798.     if ( sourceRefNum )        FSClose( sourceRefNum );
  799.         
  800.     return err;
  801. }
  802.  
  803.